package com.xtz.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.StrUtil;
import com.mysql.cj.util.StringUtils;
import com.xtz.domain.Employee;
import com.xtz.mapper.AdminEmployeeMapper;
import com.xtz.service.AdminEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * date: 2022/5/7 18:54
 *
 * @author xietianze
 */
@Service
public class AdminEmployeeServiceImpl implements AdminEmployeeService {
    @Autowired
    private AdminEmployeeMapper adminEmployeeMapper;
    @Override
    public Boolean addEmployee(Employee employee) {
        if (Objects.isNull(employee)){
            return false;
        }
        long id = new Snowflake().nextId();
        employee.setId(Long.toString(id));

        //将页面提交的密码password进行md5加密
        String password = "123456";
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        employee.setPassword(password);
        employee.setStatus(1);
        employee.setCreateTime(new Date());
        employee.setUpdateTime(new Date());
        employee.setCreateUser("1");
        employee.setUpdateUser("1");
        return adminEmployeeMapper.addEmployee(employee) > 0;

    }

    @Override
    public Employee selectByUsername(String username) {
        if (StringUtils.isNullOrEmpty(username)){
            return null;
        }
        Employee employee = adminEmployeeMapper.selectByUsername(username);

        return employee;
    }

    @Override
    public List<Employee> getEmployeePage(String name, Integer page, Integer pageSize) {
        int offset = (page - 1) * pageSize;

        return adminEmployeeMapper.selectPage(name,offset,pageSize);
    }


    @Override
    public Long getEmployeeAmount(String name) {
        return adminEmployeeMapper.selectCount(name);
    }

    @Override
    public Employee login(String username, String password) {
        Employee employee = adminEmployeeMapper.loginEmployee(username, password);
        return employee;

    }

    @Override
    public Employee selectEmployeeById(String id) {
        if (StringUtils.isNullOrEmpty(id)){
            return null;
        }
        Employee employee = adminEmployeeMapper.selectEmployeeById(id);
        return employee;
    }

    @Override
    public Boolean updateEmployeeById(Employee employee) {
        if (Objects.isNull(employee) || StrUtil.isEmpty(employee.getId())) {
            return false;
        }
        employee.setUpdateTime(new Date());

        int i = adminEmployeeMapper.updateEmployeeById(employee);
        return i > 0;
    }


}
